package com.chenjt.netty.two_socket.simple.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/8/8 11:25
 */
public class MyServerInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * 客户端一旦和服务器端连接之后，MyServerInitializer这个对象就会被创建，并且会调用initChannel这个方法
     * @param ch
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 添加解码器
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
        // 添加编码器
        pipeline.addLast(new LengthFieldPrepender(4));
        // 字符串编码器
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        // 字符串解码器
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));

        pipeline.addLast(new MyServerHandler());


    }
}
